package com.bianpai.core;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 流程上下文，用于在节点间传递数据
 */
public class FlowContext {
    private String flowId;
    private String flowInstanceId;
    private Map<String, Object> variables;
    private Map<String, NodeResult> nodeResults;
    
    public FlowContext(String flowId) {
        this.flowId = flowId;
        this.flowInstanceId = UUID.randomUUID().toString();
        this.variables = new HashMap<>();
        this.nodeResults = new HashMap<>();
    }
    
    public String getFlowId() {
        return flowId;
    }
    
    public String getFlowInstanceId() {
        return flowInstanceId;
    }
    
    public void setVariable(String key, Object value) {
        variables.put(key, value);
    }
    
    public Object getVariable(String key) {
        return variables.get(key);
    }
    
    public Map<String, Object> getVariables() {
        return variables;
    }
    
    public void setNodeResult(String nodeId, NodeResult result) {
        nodeResults.put(nodeId, result);
    }
    
    public NodeResult getNodeResult(String nodeId) {
        return nodeResults.get(nodeId);
    }
    
    public Map<String, NodeResult> getNodeResults() {
        return nodeResults;
    }
    
    /**
     * 判断指定节点是否执行成功
     * @param nodeId 节点ID
     * @return 是否成功
     */
    public boolean isNodeSuccessful(String nodeId) {
        NodeResult result = nodeResults.get(nodeId);
        return result != null && result.isSuccess();
    }
    
    /**
     * 创建上下文的快照，用于回滚
     * @return 上下文快照
     */
    public FlowContext createSnapshot() {
        FlowContext snapshot = new FlowContext(this.flowId);
        snapshot.flowInstanceId = this.flowInstanceId;
        snapshot.variables = new HashMap<>(this.variables);
        snapshot.nodeResults = new HashMap<>(this.nodeResults);
        return snapshot;
    }
}